<template>
  <div id="buildFleet">
    <el-form ref="basicMessage" :model="fleet.data" label-width="140px" label-position="left" :inline="true" :rules="rules">
      <div class="title">
        <div class="title-label"></div>
        配置基本信息
      </div>
      <div class="formData">
        <div class="chooseCreationMethod">
          <span>实例类型</span>
          <el-radio-group class="radios" v-model="buildType" @change="buildTypeChange">
            <el-radio-button label="0">VM</el-radio-button>
            <el-radio-button label="1">POD</el-radio-button>
          </el-radio-group>
        </div>
        <el-form-item prop="name">
          <template #label>
            <div class="item-label">名称</div>
            <el-tooltip effect="dark" :content="tooltip.name" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input v-model="fleet.data.name" maxlength="1024" />
        </el-form-item>
        <el-form-item prop="description">
          <template #label>
            <div class="item-label">描述</div>
            <el-tooltip effect="dark" :content="tooltip.description" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input v-model="fleet.data.description" maxlength="1024" />
        </el-form-item>
        <el-form-item prop="build_id">
          <template #label>
            <div class="item-label">应用包ID</div>
            <el-tooltip effect="dark" :content="tooltip.build_id" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.build_id" class="m-2 fleet" placeholder="请输入应用包名称进行筛选" clearable filterable>
            <el-option v-for="item in buildOptions" :key="item.value" :label="item.label" :value="item.value">
              <div class="fleetLabel">{{ item.label }}</div>
              <div class="fleetValue">{{ item.value }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="region">
          <template #label>
            <div class="item-label">区域</div>
            <el-tooltip effect="dark" :content="tooltip.region" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.region" @change="regionChange">
            <el-option v-for="item in regionOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
    </el-form>
    <el-form class="configuration" ref="tag_config" :model="fleet.data" label-position="top" v-if="buildType == '0'">
      <div class="formData">
        <div class="configurationContent" v-for="(item, index) in fleet.data.instance_tags" :key="index">
          <div class="label"><span v-if="index < 1">实例标签:</span></div>
          <div class="formcol1">
            <el-form-item :prop="'instance_tags.' + index + '.key'" :rules="tag_rules">
              <template #label v-if="index < 1">
                <div class="item-label">标签键</div>
                <el-tooltip effect="dark" :content="tooltip.instance_tags.key" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-input v-model="item.key" maxlength="36" placeholder="请输入" />
            </el-form-item>
          </div>
          <div class="formcol1">
            <el-form-item :prop="'instance_tags.' + index + '.value'">
              <template #label v-if="index < 1">
                <div class="item-label">标签值</div>
                <el-tooltip effect="dark" :content="tooltip.instance_tags.value" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-input v-model="item.value" maxlength="36" placeholder="请输入" />
            </el-form-item>
          </div>
          <div class="toport" :class="[!index && 'mg-top']">
            <el-form-item>
              <div :class="fleet.data.instance_tags.length < 2 ? 'minus' : 'add'" @click="reduce(index)">-</div>
              <div v-if="index < 1" :class="fleet.data.instance_tags.length > 9 ? 'minus' : 'add'" @click="plus()">+</div>
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <el-divider />
    <el-form ref="source_config" :model="fleet.data" label-width="140px" label-position="left" :inline="true" :rules="rules">
      <div class="title">
        <div class="title-label"></div>
        <span>配置资源信息</span>
      </div>
      <div class="formData">
        <el-form-item prop="vpc_id">
          <template #label>
            <div class="item-label">VPC ID</div>
            <el-tooltip effect="dark" :content="tooltip.vpc_id" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.vpc_id" class="m-2 fleet" @change="vpcChange" clearable filterable placeholder="请输入VPC名称进行筛选">
            <el-option v-for="item in vpcOptions" :key="item.value" :label="item.label" :value="item.value">
              <div class="fleetLabel">{{ item.label }}</div>
              <div class="fleetValue">{{ item.value }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="subnet_id" :rules="subnet_id_rules" v-if="fleet.data.vpc_id">
          <template #label>
            <div class="item-label">子网ID</div>
            <el-tooltip effect="dark" :content="tooltip.subnet_id" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.subnet_id" class="m-2 fleet" clearable filterable placeholder="请输入子网ID进行筛选">
            <el-option v-for="item in subnetOptions" :key="item.value" :label="item.label" :value="item.value">
              <div class="fleetLabel">{{ item.label }}</div>
              <div class="fleetValue">{{ item.value }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="public_ip.ip_type" :rules="rules.ip_type">
          <template #label>
            <div class="item-label">ip类型</div>
            <el-tooltip effect="dark" :content="tooltip.public_ip.ip_type" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.public_ip.ip_type" clearable>
            <el-option label="全动态BGP" value="5_bgp" />
            <el-option label="静态BGP" value="5_sbgp" />
          </el-select>
        </el-form-item>
        <el-form-item prop="public_ip.bandwidth.share_type" :rules="rules.share_type">
          <template #label>
            <div class="item-label">带宽类型</div>
            <el-tooltip effect="dark" :content="tooltip.public_ip.bandwidth.share_type" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.public_ip.bandwidth.share_type" clearable>
            <el-option label="独享带宽" value="PER" />
            <el-option label="共享带宽" value="WHOLE" />
          </el-select>
        </el-form-item>
        <el-form-item prop="public_ip.bandwidth.size" v-if="fleet.data.public_ip.bandwidth.share_type == 'PER'" :rules="rules.bandwidth">
          <template #label>
            <div class="item-label">带宽大小</div>
            <el-tooltip effect="dark" :content="tooltip.public_ip.bandwidth.size" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input v-model.number="fleet.data.public_ip.bandwidth.size" placeholder="单位：Mbps" />
        </el-form-item>
        <el-form-item prop="public_ip.bandwidth.charging_mode" v-if="fleet.data.public_ip.bandwidth.share_type == 'PER'" :rules="rules.charging_mode">
          <template #label>
            <div class="item-label">带宽计费方式</div>
            <el-tooltip effect="dark" :content="tooltip.public_ip.bandwidth.charging_mode" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.public_ip.bandwidth.charging_mode" clearable>
            <el-option label="按流量计费" value="traffic" />
            <el-option label="按带宽计费" value="bandwidth" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="fleet.data.public_ip.bandwidth.share_type == 'WHOLE'" prop="public_ip.bandwidth.id" :rules="rules.ip_id">
          <template #label>
            <div class="item-label">共享带宽ID</div>
            <el-tooltip effect="dark" :content="tooltip.public_ip.bandwidth.id" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.public_ip.bandwidth.id" class="m-2 fleet" clearable filterable placeholder="请输入共享带宽ID进行筛选">
            <el-option v-for="item in bandWidths" :key="item.value" :label="item.label" :value="item.value">
              <div class="fleetLabel">{{ item.label }}</div>
              <div class="fleetValue">{{ item.value }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="enterprise_project_id">
          <template #label>
            <div class="item-label">企业项目ID</div>
            <el-tooltip effect="dark" :content="tooltip.enterprise_project_id" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input v-model="fleet.data.enterprise_project_id" />
        </el-form-item>
        <el-form-item prop="resource_specification_id" :rules="rules.resource_specification_id">
          <template #label>
            <div class="item-label">实例规格</div>
            <el-tooltip effect="dark" :content="tooltip.instance_specification" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.resource_specification_id" class="m-2 fleet" clearable filterable placeholder="请输入实例规格进行筛选">
            <el-option v-for="item in exampleOptions" :key="item.value" :label="item.label" :value="item.value">
              <div class="fleetLabel fleetLabels">{{ item.label }}</div>
              <div class="fleetValue">{{ item.value }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="available_zones" v-if="buildType == '0'">
          <template #label>
            <div class="item-label">可用区</div>
            <el-tooltip effect="dark" :content="tooltip.available_zones" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select collapse-tags collapse-tags-tooltip v-model="fleet.data.available_zones" class="m-2 fleet" clearable placeholder="随机可用区" multiple>
            <el-option v-for="item in availableOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-divider />
      <div class="title">
        <div class="title-label"></div>
        <span>配置策略</span>
      </div>
      <div class="formData">
        <el-form-item prop="server_session_protection_policy">
          <template #label>
            <div class="item-label">会话保护策略</div>
            <el-tooltip effect="dark" :content="tooltip.server_session_protection_policy" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="fleet.data.server_session_protection_policy" clearable>
            <el-option v-for="item in server_session_protection_options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="server_session_protection_time_limit_minutes" v-if="fleet.data.server_session_protection_policy == 'TIME_LIMIT_PROTECTION'">
          <template #label>
            <div class="item-label">会话保护时长</div>
            <el-tooltip effect="dark" :content="tooltip.server_session_protection_time_limit_minutes" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input v-model.number="fleet.data.server_session_protection_time_limit_minutes" placeholder="单位：分钟" />
        </el-form-item>
      </div>
      <el-divider />
      <div class="title">
        <div class="title-label"></div>
        <span>应用运行配置</span>
      </div>
      <div class="formData">
        <el-form-item
          label-width="180px"
          prop="runtime_configuration.server_session_activation_timeout_seconds"
          :rules="server_session_activation_timeout_seconds_rules"
        >
          <template #label>
            <div class="item-label">会话激活超时时间</div>
            <el-tooltip effect="dark" :content="tooltip.runtime_configuration.server_session_activation_timeout_seconds" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input v-model.number="fleet.data.runtime_configuration.server_session_activation_timeout_seconds" placeholder="单位：秒" />
        </el-form-item>
        <el-form-item
          label-width="180px"
          prop="runtime_configuration.max_concurrent_server_sessions_per_process"
          :rules="max_concurrent_server_sessions_per_process_rules"
        >
          <template #label>
            <div class="item-label">应用最大会话数</div>
            <el-tooltip effect="dark" :content="tooltip.runtime_configuration.max_concurrent_server_sessions_per_process" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input v-model.number="fleet.data.runtime_configuration.max_concurrent_server_sessions_per_process" />
        </el-form-item>
      </div>
    </el-form>
    <el-form class="configuration" ref="configuration" :model="fleet.data" label-position="top">
      <div class="formData">
        <div class="configurationContent" v-for="(item, index) in fleet.data.runtime_configuration.process_configurations" :key="index">
          <div class="label"><span v-if="index < 1">应用进程启动配置：</span></div>
          <div class="formcol1">
            <el-form-item
              :label="index < 1 ? '启动路径' : ''"
              :prop="'runtime_configuration.process_configurations.' + index + '.launch_path'"
              :rules="configuration_rules.launch_path"
            >
              <template #label v-if="index < 1">
                <div class="item-label">启动路径</div>
                <el-tooltip effect="dark" :content="tooltip.runtime_configuration.process_configurations.launch_path" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-input v-model="item.launch_path" maxlength="1024" placeholder="示例：/local/app/launch.sh" />
            </el-form-item>
          </div>
          <div class="formcol2">
            <el-form-item :prop="'runtime_configuration.process_configurations.' + index + '.parameters'" :rules="configuration_rules.parameters">
              <template #label v-if="index < 1">
                <div class="item-label">启动参数</div>
                <el-tooltip effect="dark" :content="tooltip.runtime_configuration.process_configurations.parameters" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-input v-model="item.parameters" maxlength="1024" />
            </el-form-item>
          </div>
          <div class="formcol3">
            <el-form-item
              :prop="'runtime_configuration.process_configurations.' + index + '.concurrent_executions'"
              :rules="configuration_rules.concurrent_executions"
            >
              <template #label v-if="index < 1">
                <div class="item-label">并发启动数量</div>
                <el-tooltip effect="dark" :content="tooltip.runtime_configuration.process_configurations.concurrent_executions" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-input v-model.number="item.concurrent_executions" />
              <div :class="fleet.data.runtime_configuration.process_configurations.length < 2 ? 'minus' : 'add'" @click="minusconfig(index)">-</div>
              <div v-if="index < 1" :class="fleet.data.runtime_configuration.process_configurations.length > 49 ? 'minus' : 'add'" @click="addconfig()">+</div>
            </el-form-item>
          </div>
        </div>
      </div>
      <el-divider />
      <div class="title">
        <div class="title-label"></div>
        <span>配置入站规则</span>
      </div>
      <el-form :model="fleet.data" label-width="130px" label-position="left" :rules="rules">
        <div class="formData">
          <div>
            <el-form-item prop="security_group_ids" style="display: flex">
              <template #label>
                <div class="item-label">安全组</div>
                <el-tooltip effect="dark" :content="tooltip.inbound_permissions.protocol" placement="bottom"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-select
                collapse-tags
                collapse-tags-tooltip
                v-model="fleet.data.security_group_ids"
                class="m-2 fleet"
                clearable
                filterable
                placeholder="请输入安全组名进行筛选"
                multiple
                :multiple-limit="10"
              >
                <el-option v-for="item in securityGroup" :key="item.value" :label="item.label" :value="item.value">
                  <div class="fleetLabel">{{ item.label }}</div>
                  <div class="fleetValue">{{ item.value }}</div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div class="formData">
        <div class="communicationitem" v-for="(item, index) in fleet.data.inbound_permissions" :key="index">
          <div class="col1">
            <el-form-item :prop="'inbound_permissions.' + index + '.protocol'" :rules="configuration_rules.protocol">
              <template #label v-if="index < 1">
                <div class="item-label">协议</div>
                <el-tooltip effect="dark" :content="tooltip.inbound_permissions.protocol" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-select v-model="item.protocol"> <el-option v-for="i in protocol_options" :key="i.value" :label="i.label" :value="i.value" /> </el-select
            ></el-form-item>
          </div>
          <div class="col2">
            <el-form-item :prop="'inbound_permissions.' + index + '.ip_range'" :rules="configuration_rules.ip_range">
              <template #label v-if="index < 1">
                <div class="item-label">IP地址</div>
                <el-tooltip effect="dark" :content="tooltip.inbound_permissions.ip_range" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-input v-model="item.ip_range" minlength="9" maxlength="18" />
            </el-form-item>
          </div>
          <div class="col3">
            <el-form-item required>
              <template #label v-if="index < 1">
                <div class="item-label">起止端口</div>
                <el-tooltip effect="dark" :content="tooltip.inbound_permissions.port" placement="right"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <div class="content">
                <el-form-item :prop="'inbound_permissions.' + index + '.from_port'" :rules="configuration_rules.from_port">
                  <el-input v-model.number="item.from_port" />
                </el-form-item>
                <span class="portline">——————</span>
                <div class="toport">
                  <el-form-item :prop="'inbound_permissions.' + index + '.to_port'" :rules="configuration_rules.to_port">
                    <el-input v-model.number="item.to_port" />
                    <div :class="fleet.data.inbound_permissions.length < 2 ? 'minus' : 'add'" @click="minusport(index)">-</div>
                    <div v-if="index < 1" :class="fleet.data.inbound_permissions.length > 49 ? 'minus' : 'add'" @click="addport()">+</div>
                  </el-form-item>
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
      </div>
      <el-divider />
      <div class="title">
        <div class="title-label"></div>
        <span>配置容量</span>
      </div>
      <div class="formData flex-form">
        <div class="formData-item">
          <el-form-item prop="scaling_group_capacity.min_instance_number" :rules="rules.min_instance_number">
            <template #label>
              <div class="item-label">最小实例数</div>
              <el-tooltip effect="dark" :content="tooltip.scaling_group_capacity.tip" placement="bottom"
                ><el-icon><QuestionFilled /></el-icon
              ></el-tooltip>
            </template>
            <el-input v-model.number="fleet.data.scaling_group_capacity.min_instance_number" placeholder="单位：台" />
          </el-form-item>
        </div>
        <div class="formData-item">
          <el-form-item prop="scaling_group_capacity.max_instance_number" :rules="rules.max_instance_number">
            <template #label>
              <div class="item-label">最大实例数</div>
              <el-tooltip effect="dark" :content="tooltip.scaling_group_capacity.tip" placement="bottom"
                ><el-icon><QuestionFilled /></el-icon
              ></el-tooltip>
            </template>
            <el-input v-model.number="fleet.data.scaling_group_capacity.max_instance_number" placeholder="单位：台" />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="operateButton">
      <el-button class="btn button" @click="onReset">重置</el-button>
      <el-button class="btn new button" type="primary" @click="onSubmit">创建</el-button>
      <el-button class="btn button" @click="onDownload"><a>导出</a></el-button>
    </div>
  </div>
</template>
<style>
  .fleet {
    height: 30px;
  }
  .fleet .el-select__tags {
    height: 30px;
    white-space: nowrap;
    overflow: hidden;
    flex-wrap: nowrap;
  }
</style>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  #buildFleet {
    background-color: $blank-color;
    padding: 30px;
    margin-top: 60px;
    .chooseCreationMethod {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
      span {
        font-size: 14px;
        width: 70px;
      }
      .radios {
        margin-left: 70px;
        :deep(.el-radio-button__inner) {
          width: 200px;
          height: 30px;
          border-radius: 2px;
          font-size: 14px;
          text-align: CENTER;
          color: #8a8e99;
        }
        :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
          background-color: #ecf2ff;
          border: 1px solid #325cb0;
          color: #325cb0;
          box-shadow: none;
        }
      }
    }
    .mg-top {
      margin-top: 30px;
    }
    .title {
      display: flex;
      align-items: center;
      margin-bottom: 36px;
      font-weight: bold;
      font-size: 14px;
      .title-label {
        width: 4px;
        height: 14px;
        background: #325cb0;
        border-radius: 0px;
        margin-right: 6px;
      }
    }
    label {
      color: #333333;
    }
    .formData {
      margin-left: 10px;
    }
    .item-label {
      color: $text-color;
    }
    .el-form-item {
      width: 620px;
      margin-right: 180px;
      margin-bottom: 30px;
      :deep(.el-form-item__label) {
        display: inline-flex;
        align-items: center;
      }
      :deep(.el-form-item__label::before) {
        margin-left: -10px;
      }
    }
    .configuration {
      .el-select {
        width: 360px;
      }
      .configurationContent {
        display: flex;
        .label {
          font-size: 14px;
          width: 140px;
          color: #333333;
          span {
            display: block;
            width: 130px;
          }
        }
        .formcol1 {
          .el-form-item {
            width: 450px;
            margin-right: 25px;
            margin-bottom: 28px;
          }
        }
        .formcol2 {
          .el-form-item {
            width: 240px;
            margin-right: 60px;
            margin-bottom: 28px;
          }
        }
        .formcol3 {
          display: flex;
          :deep(.el-form-item__content) {
            flex-wrap: nowrap;
          }
          .el-form-item {
            width: 424px;
            margin-bottom: 28px;
          }
          .el-input {
            width: 240px;
            margin-right: 80px;
          }
          :deep(.el-input__wrapper) {
            width: 418px;
          }
        }
      }
    }
    .communicationitem {
      display: flex;
      justify-content: flex-start;
      flex-wrap: nowrap;
      margin-left: 140px;
      .col1 {
        height: 60px;
        .el-form-item {
          width: 150px;
          margin-bottom: 28px;
          margin-right: 60px;
        }
      }
      .col2 {
        height: 60px;
        .el-form-item {
          width: 480px;
          margin-bottom: 28px;
          margin-right: 60px;
        }
      }
      .col3 {
        height: 60px;
        .el-form-item {
          width: 120px;
          margin-right: 0;
          margin-bottom: 28px;
        }
        .portline {
          width: 40px;
          color: #e0e2e9;
        }
        .content {
          display: flex;
        }
        .el-input {
          width: 120px;
        }
        .toport {
          display: flex;
          :deep(.el-form-item__content) {
            flex-wrap: nowrap;
          }
          .el-input {
            width: 120px;
            margin-right: 80px;
          }
          .el-form-item {
            width: 320px;
            margin-bottom: 20px;
          }
          .operation {
            display: flex;
            justify-content: space-between;
          }
        }
      }
    }

    .communicationitem:nth-child(1) {
      height: 90px;
    }
    .toport {
      display: flex;
      .el-form-item {
        width: 320px;
        margin-bottom: 20px;
      }
    }
    .operate {
      margin-left: 80px;
    }
    .flex-form {
      display: flex;
      .formData-item {
        width: 30.3%;
        .el-form-item {
          display: flex;
          align-items: center;
          :deep(.el-form-item__label) {
            margin: 0 20px 0 0;
          }
        }
        .el-input {
          width: 250px;
        }
      }
    }
  }
  .el-select-dropdown.is-multiple .el-select-dropdown__item.selected::after {
    width: 16px;
    height: 40px;
    background-color: #325cb0;
  }
  .el-select-dropdown.is-multiple .el-select-dropdown__item.selected {
    color: #325cb0;
  }
  .checkboxAll {
    margin-right: 10px;
  }
  .el-select-dropdown__item.is-disabled input {
    cursor: not-allowed;
    pointer-events: none;
  }
</style>
<script lang="ts" setup>
  import regions from '@/tips/regions.json'
  import appStore from '@/store'
  import { onMounted, reactive, ref, watch } from 'vue'
  import FleetsService, { CreateFleetRequestBody, ProcessConfiguration, FleetType } from '@/api/fleetsService'
  import type { FormInstance, FormRules, FormItemRule } from 'element-plus'
  import ApplicationService, { builds } from '@/api/applicationService'
  import UserService from '@/api/userService'
  import { ElMessage } from 'element-plus'
  import data from '../../tips/fleetTip.json'
  import router from '@/router'
  const props = defineProps(['data'])
  const buildType = ref('0')
  const basicMessage = ref<FormInstance>()
  const configuration = ref<FormInstance>()
  const tag_config = ref<FormInstance>()
  const source_config = ref<FormInstance>()
  const tooltip = reactive(data)
  interface optionList {
    value: string
    label: string
  }
  const getbucket = {
    project_id: appStore.userStore.project_id,
    region: appStore.userStore.region,
    resource_specification: '',
    vpc_id: '',
    name: '',
    offset: 1,
    limit: 10
  }
  const build = {
    project_id: appStore.userStore.project_id,
    state: 'READY'
  }
  let vpcOptions: optionList[] = reactive([])
  let availableOptions: optionList[] = reactive([])
  let subnetOptions: optionList[] = reactive([])
  let buildOptions: optionList[] = reactive([])
  let bandWidths: optionList[] = reactive([])
  let securityGroup: optionList[] = reactive([])
  const regionChange = async (val: any) => {
    if (val) {
      let res = await UserService.getOrigininfo(appStore.userStore.name, val)
      let projectId
      Object.keys(res.data.origins).forEach((key) => {
        projectId = res.data.origins[key].project_id
      })
      getbucket.project_id = projectId || ''
      getResourceSpecification()
    }
  }
  const getSecurityGroup = async () => {
    let res = await UserService.getSecurityGroup(getbucket)
    if (res.status == 200) {
      res.data.forEach((item: any) => {
        securityGroup.push({
          label: item.security_group_name,
          value: item.security_group_id
        })
      })
    }
  }
  const buildTypeChange = (val: any) => {
    if (val) {
      fleet.data.build_id = ''
      fleet.data.resource_specification_id = ''
      getApplications()
      getResourceSpecification()
    }
  }
  const getApplications = async () => {
    let res = await ApplicationService.getApplications(build)
    if (res.status === 200) {
      buildOptions.length = 0
      res.data.builds.forEach((item: any) => {
        if (item.state == 'READY' && item.build_type == 'VM' && buildType.value == '0') {
          buildOptions.push({
            value: item.build_id,
            label: `${item.name}/${item.version}`
          })
        }
        if (item.state == 'READY' && item.build_type == 'POD' && buildType.value == '1') {
          buildOptions.push({
            value: item.build_id,
            label: `${item.name}/${item.version}`
          })
        }
      })
    }
  }
  const getVpcName = async () => {
    let res = await UserService.getVpcList(getbucket)
    if (res.status == 200) {
      vpcOptions.length = 0
      res.data.vpc_list.forEach((item: any) => {
        vpcOptions.push({
          value: item.vpc_id,
          label: item.vpc_name
        })
      })
    }
  }
  const getAvailableZone = async () => {
    let res = await UserService.getAvailableZone(getbucket)
    if (res.status == 200) {
      availableOptions.length = 0
      res.data.forEach((item: any) => {
        availableOptions.push({
          value: item.available_zone_id,
          label: item.available_zone_name
        })
      })
    }
  }
  const getIdName = async () => {
    let res = await UserService.getIdList(getbucket)
    if (res.status == 200) {
      bandWidths.length = 0
      res.data.bandwidths.forEach((item: any) => {
        bandWidths.push({
          value: item.id,
          label: item.name
        })
      })
    }
  }
  const getSubnetName = async (id: any) => {
    getbucket.vpc_id = id
    let res = await UserService.getSubnetList(getbucket)
    if (res.status == 200) {
      subnetOptions.length = 0
      res.data.subnet_list.forEach((item: any) => {
        subnetOptions.push({
          value: item.subnet_id,
          label: item.subnet_name
        })
      })
    }
  }
  let exampleOptions: optionList[] = reactive([])
  const getResourceSpecification = async () => {
    let res = await UserService.getInstanceList(getbucket)
    if (res.status == 200 && res.data.resource_specifications) {
      exampleOptions.length = 0
      res.data.resource_specifications.forEach((item: any) => {
        if (item.instance_type == 'VM' && buildType.value == '0') {
          exampleOptions.push({
            value: item.id,
            label: `${item.name}/${item.resource_specification}`
          })
        }
        if (item.instance_type == 'POD' && buildType.value == '1') {
          exampleOptions.push({
            value: item.id,
            label: `${item.name}/${item.resource_specification}`
          })
        }
      })
    }
  }
  const vpcChange = (val: any) => {
    if (val) {
      getSubnetName(val)
    }
    fleet.data.subnet_id = ''
  }
  let form: CreateFleetRequestBody = reactive({
    name: '',
    build_id: '',
    subnet_id: '',
    instance_type: '',
    runtime_configuration: {
      process_configurations: [Object()]
    },
    inbound_permissions: [Object()],
    instance_tags: [{ key: '', value: '' }],
    description: '',
    region: '',
    bandwidth: '',
    security_group_ids: [],
    available_zones: [],
    resource_specification_id: '',
    server_session_protection_policy: '',
    server_session_protection_time_limit_minutes: '',
    resource_creation_limit_policy: Object(),
    vpc_id: '',
    enterprise_project_id: '',
    public_ip: {
      ip_type: '',
      bandwidth: {
        share_type: '',
        size: '',
        charging_mode: 'traffic',
        id: ''
      }
    },
    scaling_group_capacity: Object()
  })
  let fleet = reactive({
    data: form
  })
  const tagValidate = (rule: any, value: any, callback: any) => {
    let index = Number(rule.field.split('.')[1])
    if (fleet.data.instance_tags[index].value && !value) {
      callback(new Error('请输入标签键'))
    } else {
      callback()
    }
  }

  const protectionTimeValidate = (rule: any, value: any, callback: any) => {
    if (fleet.data.server_session_protection_policy == 'TIME_LIMIT_PROTECTION' && !value) {
      callback(new Error('请输入会话保护时长'))
    } else {
      callback()
    }
  }
  const portValidate = (rule: any, value: any, callback: any) => {
    let index = Number(rule.field.split('.')[1])
    if (fleet.data.inbound_permissions[index].to_port < fleet.data.inbound_permissions[index].from_port) {
      callback(new Error('起始端口要小于等于终止端口'))
    } else {
      callback()
    }
  }
  const subnet_id_Validate = (rule: any, value: any, callback: any) => {
    if (fleet.data.vpc_id && !value) {
      callback(new Error('请选择子网'))
    } else {
      callback()
    }
  }

  const launch_path_Validate = (rule: any, value: any, callback: any) => {
    if (!(value.startsWith('/local/app/') || value.startsWith('c:/local/app/') || value.startsWith('C:/local/app/'))) {
      callback(new Error('请选择正确的启动路径'))
    } else {
      callback()
    }
  }
  const minMax = (rule: any, value: any, callback: any) => {
    if (fleet.data.scaling_group_capacity.max_instance_number) {
      if (value <= fleet.data.scaling_group_capacity.max_instance_number) {
        callback()
      } else {
        callback(new Error('最小实例数要小于最大实例数'))
      }
    } else if (!value) {
      callback()
    } else {
      callback(new Error('请填写最大实例数'))
    }
  }
  const maax = (rule: any, value: any, callback: any) => {
    if (fleet.data.scaling_group_capacity.min_instance_number) {
      callback()
    } else if (!value) {
      callback()
    } else {
      callback(new Error('请填写最小实例数'))
    }
  }
  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入队列名称', trigger: ['change', 'blur'] }],
    build_id: [{ required: true, message: '请输入应用包ID', trigger: ['change', 'blur'] }],
    region: [{ required: true, message: '请选择区域', trigger: ['change', 'blur'] }],
    instance_type: [{ required: true, message: '请选择实例类型', trigger: ['change', 'blur'] }],
    ip_type: [{ required: true, message: '请选择ip类型', trigger: ['change', 'blur'] }],
    share_type: [{ required: true, message: '请选择带宽类型', trigger: ['change', 'blur'] }],
    resource_specification_id: [{ required: true, message: '请选择实例规格', trigger: ['change', 'blur'] }],
    charging_mode: [{ required: true, message: '请选择带宽计费方式', trigger: ['change', 'blur'] }],
    ip_id: [{ required: true, message: '请选择共享带宽ID', trigger: ['change', 'blur'] }],
    min_instance_number: [
      {
        type: 'number',
        min: 1,
        message: '请输入大于0的数字',
        trigger: ['change', 'blur']
      },
      {
        validator: minMax,
        trigger: ['change', 'blur']
      }
    ],
    max_instance_number: [
      {
        type: 'number',
        min: 1,
        message: '请输入大于0的数字',
        trigger: ['change', 'blur']
      },
      {
        validator: maax,
        trigger: ['change', 'blur']
      }
    ],
    bandwidth: [
      {
        type: 'number',
        min: 1,
        max: 2000,
        required: true,
        message: '请输入1-2000范围内的数字',
        trigger: ['change', 'blur']
      }
    ],
    server_session_protection_time_limit_minutes: [
      {
        type: 'number',
        min: 5,
        max: 1440,
        message: '请输入5-1440范围内的数字',
        trigger: ['change', 'blur']
      },
      { validator: protectionTimeValidate, trigger: ['change', 'blur'] }
    ]
  })

  const server_session_activation_timeout_seconds_rules: FormItemRule[] = [
    {
      required: true,
      type: 'number',
      min: 1,
      max: 600,
      message: '请输入1-600范围内的数字',
      trigger: ['change', 'blur']
    }
  ]

  const max_concurrent_server_sessions_per_process_rules: FormItemRule[] = [
    {
      required: true,
      type: 'number',
      min: 1,
      max: 50,
      message: '请输入1-50范围内的数字',
      trigger: ['change', 'blur']
    }
  ]
  const tag_rules: FormItemRule[] = [
    {
      validator: tagValidate,
      trigger: ['change', 'blur']
    }
  ]

  const subnet_id_rules: FormItemRule[] = [
    {
      validator: subnet_id_Validate,
      trigger: ['change', 'blur']
    }
  ]

  const configuration_rules = reactive<FormRules>({
    launch_path: [
      { required: true, message: '请输入启动路径', trigger: ['change', 'blur'] },
      { validator: launch_path_Validate, trigger: ['change', 'blur'] }
    ],
    parameters: [{ pattern: /^[A-Za-z\-\=\s\d]{0,1024}$/, message: '请输入正确的启动参数', trigger: ['change', 'blur'] }],
    concurrent_executions: [
      {
        required: true,
        type: 'number',
        min: 1,
        max: 50,
        message: '请输入1-50范围内的数字',
        trigger: ['change', 'blur']
      }
    ],
    protocol: [{ required: true, message: '请选择协议', trigger: ['change', 'blur'] }],
    ip_range: [
      { required: true, message: '请输入IP地址', trigger: ['change', 'blur'] },
      {
        pattern: /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))).){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\/([0-9]$|[1-2][0-9]|3[0-2])$/,
        message: '请输入正确的ip地址',
        trigger: ['change', 'blur']
      }
    ],
    from_port: [
      {
        required: true,
        type: 'number',
        min: 1025,
        max: 60000,
        message: '请输入1025-60000范围内的数字',
        trigger: ['change', 'blur']
      },
      { validator: portValidate, trigger: 'blur' }
    ],
    to_port: [
      {
        required: true,
        type: 'number',
        min: 1025,
        max: 60000,
        message: '请输入1025-60000范围内的数字',
        trigger: ['change', 'blur']
      },
      { validator: portValidate, trigger: ['change', 'blur'] }
    ]
  })
  const protocol_options = [
    {
      value: 'TCP',
      label: 'TCP'
    },
    {
      value: 'UDP',
      label: 'UDP'
    }
  ]

  const submitParam: FleetType = {
    project_id: appStore.userStore.project_id,
    fleet: JSON.parse(JSON.stringify(fleet.data))
  }

  const server_session_protection_options = [
    {
      value: 'NO_PROTECTION',
      label: '不保护'
    },
    {
      value: 'TIME_LIMIT_PROTECTION',
      label: '限时保护'
    }
  ]

  const onReset = () => {
    basicMessage.value?.resetFields()
    configuration.value?.resetFields()
    source_config.value?.resetFields()
    tag_config.value?.resetFields()
    fleet.data = form
    localStorage.removeItem('fleetForm')
  }
  let creating = ref(false)
  const onSubmit = async () => {
    try {
      if (creating.value) return
      let basicMessageValid = await basicMessage.value?.validate((valid) => {
        return valid
      })

      let configurationValid = await configuration.value?.validate((valid) => {
        return valid
      })

      let tagConfigValid = await tag_config.value?.validate((valid) => {
        return valid
      })

      let sourceConfigValid = await source_config.value?.validate((valid) => {
        return valid
      })

      if (basicMessageValid && configurationValid && sourceConfigValid) {
        submitParam.fleet = JSON.parse(JSON.stringify(fleet.data))
        for (let item in submitParam.fleet) {
          if (typeof (submitParam.fleet as any)[item] === 'undefined' || (submitParam.fleet as any)[item] === null || (submitParam.fleet as any)[item] === '') {
            delete (submitParam.fleet as any)[item]
          }
        }
        submitParam.fleet.instance_tags = submitParam.fleet.instance_tags?.filter((item) => item.key != '')
        submitParam.fleet.runtime_configuration.process_configurations = submitParam.fleet.runtime_configuration.process_configurations?.filter(
          (value) => Object.keys(value).length !== 0
        )
        submitParam.fleet.inbound_permissions = submitParam.fleet.inbound_permissions?.filter((value) => Object.keys(value).length !== 0)
        submitParam.fleet.public_ip.bandwidth.size ? '' : (submitParam.fleet.public_ip.bandwidth.size = 1)
        submitParam.fleet.public_ip.bandwidth.share_type == 'WHOLE' ? (submitParam.fleet.public_ip.bandwidth.charging_mode = 'traffic') : ''
        if (typeof submitParam.fleet.scaling_group_capacity.min_instance_number == 'string') {
          submitParam.fleet.scaling_group_capacity = {}
        }
        if (buildType.value == '0') {
          submitParam.fleet.instance_type = 'VM'
        } else {
          submitParam.fleet.instance_type = 'POD'
        }
        creating.value = true
        let res = await FleetsService.createFleet(submitParam)
        if (res.status === 201) {
          creating.value = false
          ElMessage({
            message: '创建成功！',
            type: 'success'
          })
          localStorage.removeItem('fleetForm')
          router.push({ name: 'runningState' })
        }
      }
    } catch (error) {
      creating.value = false
      ElMessage.error('创建失败')
    }
  }
  const minusport = (index: number) => {
    if (fleet.data.inbound_permissions.length < 2) return
    fleet.data.inbound_permissions.splice(index, 1)
  }

  const addport = () => {
    if (fleet.data.inbound_permissions.length > 49) return
    fleet.data.inbound_permissions.push(Object())
  }
  const minusconfig = (index: number) => {
    if (fleet.data.runtime_configuration.process_configurations!.length < 2) return
    fleet.data.runtime_configuration.process_configurations!.splice(index, 1)
  }

  const addconfig = () => {
    if (fleet.data.runtime_configuration.process_configurations!.length > 49) return
    fleet.data.runtime_configuration.process_configurations!.push(Object())
  }
  const reduce = (index: any) => {
    if (fleet.data.instance_tags.length < 2) return
    fleet.data.instance_tags.splice(index, 1)
  }
  const plus = () => {
    if (fleet.data.instance_tags.length > 9) return
    fleet.data.instance_tags.push({
      key: '',
      value: ''
    })
  }
  const getForm = () => {
    if (props.data) {
      fleet.data = JSON.parse(props.data)
    }
    if (!fleet.data.instance_tags) {
      fleet.data.instance_tags = [{ key: '', value: '' }]
    }
    if (!fleet.data.inbound_permissions) {
      fleet.data.inbound_permissions = [Object()]
    }
    if (!fleet.data.runtime_configuration) {
      fleet.data.runtime_configuration = { process_configurations: [Object()] }
    } else if (!fleet.data.runtime_configuration.process_configurations) {
      fleet.data.runtime_configuration.process_configurations = [Object()]
    }
  }

  defineExpose({ getForm })

  watch(
    () => props.data,
    (newValue, oldValue) => {
      fleet.data = JSON.parse(newValue)
      if (!fleet.data.instance_tags) {
        fleet.data.instance_tags = [{ key: '', value: '' }]
      }
      if (!fleet.data.inbound_permissions) {
        fleet.data.inbound_permissions = [Object()]
      }
      if (!fleet.data.runtime_configuration) {
        fleet.data.runtime_configuration = { process_configurations: [Object()] }
      } else if (!fleet.data.runtime_configuration.process_configurations) {
        fleet.data.runtime_configuration.process_configurations = [Object()]
      }
    }
  )

  watch(
    () => fleet.data,
    (newValue, oldValue) => {
      localStorage.setItem('fleetForm', JSON.stringify(newValue))
    },
    { deep: true }
  )
  watch(
    () => fleet.data.vpc_id,
    (newValue, oldValue) => {
      if (newValue) {
        getSubnetName(newValue)
      }
    },
    { deep: true }
  )
  onMounted(() => {
    if (localStorage.getItem('fleetForm')) {
      fleet.data = JSON.parse(localStorage.getItem('fleetForm') as string)
      fleet.data.runtime_configuration.process_configurations = fleet.data.runtime_configuration.process_configurations?.filter(
        (value) => Object.keys(value).length !== 0
      )
      fleet.data.inbound_permissions = fleet.data.inbound_permissions?.filter((value) => Object.keys(value).length !== 0)
      if (fleet.data.runtime_configuration.process_configurations.length < 1) {
        fleet.data.runtime_configuration.process_configurations.push(Object())
      }
      if (fleet.data.inbound_permissions.length < 1) {
        fleet.data.inbound_permissions.push(Object())
      }
    }
  })
  const regionOptions: optionList[] = reactive([])
  const regionData: { [key: string]: string } = reactive(regions)
  const getRegion = async () => {
    let res = await UserService.getRegion()
    let regionArr = res.data.regions
    if (regionArr.length) {
      regionArr.forEach((element: any, index: any) => {
        regionOptions.length = 0
        regionOptions.push({
          value: regionArr[index],
          label: regionData[element]
        })
      })
      fleet.data.region = regionArr[0]
    }
  }
  const onDownload = () => {
    let link = document.createElement('a')
    link.download = 'fleet.json'
    link.href = 'data:text/plain,' + JSON.stringify(fleet.data)
    link.click()
  }

  getVpcName()
  getApplications()
  getSecurityGroup()
  getRegion()
  getIdName()
  getResourceSpecification()
  getAvailableZone()
</script>
